﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using WP.Commons;
using WP.DB;
using WP.Modules;


using WP.RM.BusinessRule;
using WP.RM.BusinessLogical;
using WP.RM.DataAccess;

namespace WP.RM.Form
{
    public partial class frmRMProductBOMSemiQry : BaseQryRpt 
    {

        private bool[] mDtlColumnReadOnlyArray;
        private DBAccess mdbcon = new DBAccess(false, false);
        private string mstrNodeCondition = string.Empty;
        private bool mblnAlreadyLoad = false;
        private bool mblnIsLoad = false;
        public frmRMProductBOMSemiQry()
        {
            InitializeComponent();
            LoadAllControl(new ArrayList(this.Controls));           
            this.MinimumSize = this.Size;
        }

        private void InitControl()
        {
            mblnIsLoad = true;
            string strSQL = string.Empty;
            DBAccess dbcon = new DBAccess(false, false);
            cmbCategory.Items.Clear();
            strSQL = "select * from rmCategory order by CategoryName";
            DataTable dtFill = dbcon.GetDataTable(strSQL);
            cmbCategory.Items.Add("All");
            foreach (DataRow drFill in dtFill.Rows)
            {
                cmbCategory.Items.Add(drFill["CategoryName"]);
            }
            cmbCategory.SelectedIndex = 0;
            cmbSet.Items.Clear();
            strSQL = "select * from rmSet order by SetName";
            dtFill = dbcon.GetDataTable(strSQL);
            cmbSet.Items.Add("All");
            foreach (DataRow drFill in dtFill.Rows)
            {
                cmbSet.Items.Add(drFill["SetName"]);
            }
            cmbSet.SelectedIndex = 0;
            mblnIsLoad = false ;
        }
        
        private void FillTree()
        {
            DBAccess dbcon = new DBAccess(false, false);
            string strSQL = "select TypeId,TypeName,RecID from RMProductFirstType order by TypeId";
            DataTable dtItem = dbcon.GetDataTable(strSQL);
            foreach (DataRow drType in dtItem.Rows)
            {
                TreeNode tvNode = new TreeNode(CvtFunc.ToString(drType["TypeId"]) + "-" + CvtFunc.ToString(drType["TypeName"]));
                this.tvTree.Nodes.Add(tvNode);
                int intRow = 0;
                strSQL = "select TypeId,TypeName from RMProductSecondType where parentid='" + CvtFunc.ToString(drType["RecID"]) + "'";
                DataTable dtDtl = dbcon.GetDataTable(strSQL);
                foreach (DataRow drDtl in dtDtl.Rows)
                {
                    tvNode.Nodes.Add(CvtFunc.ToString(drDtl["TypeId"]) + "-" + CvtFunc.ToString(drDtl["TypeName"]));
                }
            }
            dbcon.CloseCon();
        }

        private void InitGrid()
        {
            this.dgList.Columns.Clear();
            this.dgList.Rows.Clear();

            DataGridViewTextBoxColumn colRowSeqNo = new DataGridViewTextBoxColumn();
            colRowSeqNo.HeaderText = "序号";
            colRowSeqNo.Visible = true;
            colRowSeqNo.Name = "RowSeqNo";
            colRowSeqNo.Width = 50;
            colRowSeqNo.ReadOnly = true;

            DataGridViewTextBoxColumn colCategoryName = new DataGridViewTextBoxColumn();
            colCategoryName.HeaderText = "产品名称";
            colCategoryName.Width = 150;
            colCategoryName.Name = "CategoryName";
            colCategoryName.ReadOnly = false;
            colCategoryName.Visible = true;


            DataGridViewTextBoxColumn colSetName = new DataGridViewTextBoxColumn();
            colSetName.HeaderText = "产品名称";
            colSetName.Width = 150;
            colSetName.Name = "SetName";
            colSetName.ReadOnly = false;
            colSetName.Visible = true;

            DataGridViewTextBoxColumn colProductName = new DataGridViewTextBoxColumn();
            colProductName.HeaderText = "产品名称";
            colProductName.Width = 150;
            colProductName.Name = "ProductName";
            colProductName.ReadOnly = false;
            colProductName.Visible = true;

            DataGridViewTextBoxColumn colTechnicsName = new DataGridViewTextBoxColumn();
            colTechnicsName.HeaderText = "工艺名称";
            colTechnicsName.Width = 150;
            colTechnicsName.Name = "TechnicsName";
            colTechnicsName.ReadOnly = false;
            colTechnicsName.Visible = true;

            DataGridViewTextBoxColumn colQty = new DataGridViewTextBoxColumn();
            colQty.HeaderText = "批量";
            colQty.Width = 80;
            colQty.Name = "Quantity";
            colQty.ReadOnly = true;
            colQty.Visible = true;

            DataGridViewTextBoxColumn colTotalDetailCost = new DataGridViewTextBoxColumn();
            colTotalDetailCost.HeaderText = "额定成本";
            colTotalDetailCost.Width = 150;
            colTotalDetailCost.Name = "TotalDetailCost";
            colTotalDetailCost.ReadOnly = false;
            colTotalDetailCost.Visible = true;

            DataGridViewTextBoxColumn colTotalLabourCost = new DataGridViewTextBoxColumn();
            colTotalLabourCost.HeaderText = "人工成本";
            colTotalLabourCost.Width = 150;
            colTotalLabourCost.Name = "TotalLabourCost";
            colTotalLabourCost.ReadOnly = false;
            colTotalLabourCost.Visible = true;

            DataGridViewTextBoxColumn colTotalWastageCost = new DataGridViewTextBoxColumn();
            colTotalWastageCost.HeaderText = "耗损成本";
            colTotalWastageCost.Width = 150;
            colTotalWastageCost.Name = "TotalWastageCost";
            colTotalWastageCost.ReadOnly = false;
            colTotalWastageCost.Visible = true;

            DataGridViewTextBoxColumn colTotalWorkCost = new DataGridViewTextBoxColumn();
            colTotalWorkCost.HeaderText = "项目分摊";
            colTotalWorkCost.Width = 150;
            colTotalWorkCost.Name = "TotalWorkCost";
            colTotalWorkCost.ReadOnly = true;
            colTotalWorkCost.Visible = true;

            this.dgList.Columns.AddRange(new DataGridViewColumn[] { colRowSeqNo, colCategoryName,colSetName , colProductName, colTechnicsName, colQty, colTotalDetailCost, colTotalLabourCost, colTotalWastageCost });

            mDtlColumnReadOnlyArray = new bool[dgList.Columns.Count];
            string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < dgList.Columns.Count; i++)
            {
                mDtlColumnReadOnlyArray[i] = dgList.Columns[i].ReadOnly;
                if (ColumnWidthArray.Length == dgList.Columns.Count) dgList.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
            }

            this.dgList.EditMode = DataGridViewEditMode.EditOnEnter;
            this.dgList.RowTemplate.Height = 20;
            this.dgList.RowHeadersWidth = 23;
            this.dgList.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
            this.dgList.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
            this.dgList.ColumnHeadersHeight = 30;
            this.dgList.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            this.dgList.SelectionMode = DataGridViewSelectionMode.CellSelect;
            this.dgList.AllowUserToResizeRows = false;
        }

        private void SetQryData()
        {
           
            string strSQL = string.Empty;
            bool blnAddCol = false;
            DataFunctions.DelTemporyTable( mdbcon,  "#tmpSemiProdCost" );
            strSQL = @"select rmProductBOMHdr.RecID,rmProductBOMHdr.CategoryID,rmProduct.CategoryName,rmProductBOMHdr.SetID,
                       rmProduct.SetName,rmProductBOMHdr.ProductID,rmProductBOMHdr.ProductFItemID,rmProductBOMHdr.ProductName,rmProductBOMHdr.TechnicsName 
                       into #tmpSemiProdCost from rmProductBOMHdr 
                       inner join rmProduct on rmProductBOMHdr.ProductFItemID=rmProduct.ProductFItemID where 1=1 and approval=1";
            if (cmbCategory.Text != "All")
            {
                strSQL += " and rmProductBOMHdr.CategoryName='" + cmbCategory.Text + "'";
            }
            if (cmbSet.Text != "All")
            {
                strSQL += " and rmProductBOMHdr.SetName='" + cmbSet.Text + "'";
            }
            if (mstrNodeCondition != "") strSQL += " and " + mstrNodeCondition;
            mdbcon.ExecuteSql(strSQL);
            strSQL = "select * from #tmpSemiProdCost";
            DataTable dtSel = mdbcon.GetDataTable(strSQL);

            strSQL = " select distinct SemiCode,SemiName from dbo.imSemiProduct Order By SemiCode";
            DataTable dtSemiCol = mdbcon.GetDataTable ( strSQL );
            int intCol = 1;
            foreach (DataRow drSemiCol in dtSemiCol.Rows)
            {
                strSQL = "Alter Table #tmpSemiProdCost Add ColSemiCode" + intCol + " varchar(100) not null default ''  ";
                mdbcon.ExecuteSql(strSQL);
                strSQL = "Alter Table #tmpSemiProdCost Add ColSemiName" + intCol + " varchar(100) not null default ''  ";
                mdbcon.ExecuteSql(strSQL);
                strSQL = "Alter Table #tmpSemiProdCost Add ColQty" + intCol + "  Decimal(18,2) not null default 0 ";
                mdbcon.ExecuteSql(strSQL);
                strSQL = "Alter Table #tmpSemiProdCost Add ColLaborCost" + intCol + " Decimal(18,2) not null default 0  ";
                mdbcon.ExecuteSql(strSQL);
                strSQL = "Alter Table #tmpSemiProdCost Add ColBOMCost" + intCol + " Decimal(18,2) not null default 0  ";
                mdbcon.ExecuteSql(strSQL);
                intCol++;
            }

            foreach (DataRow drSel in dtSel.Rows)
            {
                mblnAlreadyLoad = true;
                #region 获得所有半成品               
                strSQL = " select distinct SemiCode,SemiName from dbo.imSemiProduct Order By SemiCode";
                dtSemiCol = mdbcon.GetDataTable ( strSQL );
                intCol = 1;
                foreach (DataRow drSemiCol in dtSemiCol.Rows)
                {                   
                    //WorkCost  工时费用
                    //LabourCost 人工成本
                    //BOMCost 材料成本
                    strSQL = "UPDATE #tmpSemiProdCost Set ColSemiCode" + intCol + "='" + drSemiCol["SemiCode"] + "' Where RecID='" + drSel["RecID"] + "'";
                    mdbcon.ExecuteSql(strSQL);

                    strSQL = @"UPDATE #tmpSemiProdCost Set ColQty{0}=B.Quantity From 
                               (select sum(quantity) as Quantity,ProductFItemID,SetID,CategoryID from rmProductBOMSemi where
                               ProductFItemID='{1}' and SetID='{2}' and CategoryID='{3}' and TechnicsName='{4}' and SemiCode='{5}'
                               Group By ProductFItemID,SetID,CategoryID,TechnicsName) B 
                               Where #tmpSemiProdCost.ProductFItemID=B.ProductFItemID and #tmpSemiProdCost.SetID=B.SetID and #tmpSemiProdCost.CategoryID=B.CategoryID
                              ";
                    strSQL = string.Format(strSQL, intCol, drSel["ProductFItemID"], drSel["SetID"]
                                                 , drSel["CategoryID"], drSel["TechnicsName"] ,drSemiCol["SemiCode"]                                                 
                                                 ); 
                    mdbcon.ExecuteSql(strSQL);

                    strSQL = @"UPDATE #tmpSemiProdCost Set ColLaborCost{0}=isnull(B.WorkCost,0)+isnull(B.LabourCost,0) From 
                               (Select sum(WorkCost) as WorkCost, sum(LabourCost) as LabourCost, ProductFItemID,SetID,CategoryID from rmProductBOMSemi where
                               ProductFItemID='{1}' and SetID='{2}' and CategoryID='{3}' and TechnicsName='{4}' and SemiCode='{5}'
                               Group By ProductFItemID,SetID,CategoryID,TechnicsName) B 
                               Where #tmpSemiProdCost.ProductFItemID=B.ProductFItemID and #tmpSemiProdCost.SetID=B.SetID and #tmpSemiProdCost.CategoryID=B.CategoryID
                               ";
                    strSQL = string.Format(strSQL, intCol, drSel["ProductFItemID"], drSel["SetID"]
                                                 , drSel["CategoryID"], drSel["TechnicsName"], drSemiCol["SemiCode"]);
                    mdbcon.ExecuteSql(strSQL);

                    strSQL = @"UPDATE #tmpSemiProdCost Set ColBOMCost{0}=isnull(B.BomCost,0) From 
                               (Select sum(BomCost) as BomCost, ProductFItemID,SetID,CategoryID from rmProductBOMSemi where
                               ProductFItemID='{1}' and SetID='{2}' and CategoryID='{3}' and TechnicsName='{4}' and SemiCode='{5}'
                               Group By ProductFItemID,SetID,CategoryID,TechnicsName) B 
                               Where #tmpSemiProdCost.ProductFItemID=B.ProductFItemID and #tmpSemiProdCost.SetID=B.SetID and #tmpSemiProdCost.CategoryID=B.CategoryID";
                    strSQL = string.Format(strSQL, intCol, drSel["ProductFItemID"], drSel["SetID"]
                                                 , drSel["CategoryID"], drSel["TechnicsName"], drSemiCol["SemiCode"]);
                    mdbcon.ExecuteSql(strSQL); 

                    intCol++;
                }               
                #endregion
            }
        }


        private void FillGrid()
        {
            if (mblnIsLoad) return;
            string strSQL = string.Empty;
            if (!mblnAlreadyLoad)
            {
                SetQryData();
            }

            strSQL = @"select * from #tmpSemiProdCost Where 1=1";
            if (cmbCategory.Text != "All")
            {
                strSQL +=" and CategoryName='"+ cmbCategory.Text +"'";
            }
            if (cmbSet.Text != "All")
            {
                strSQL +=" and SetName='"+ cmbSet.Text +"'";
            }
            if (mstrNodeCondition != "") strSQL += " and " + mstrNodeCondition.Replace("rmProductBOMHdr.", "");
            string strLoadSQL = strSQL;
            if (mdbcon.GetDataTable(strSQL).Rows.Count == 0)
            {
                SetQryData();
            }

            if (mblnAlreadyLoad)
            {
                #region 材料成本
                this.dgList.Con = mdbcon.Con;
                this.dgList.Sql = strLoadSQL;

                this.dgList.Columns["CategoryName"].HeaderText = "类别名称";
                this.dgList.Columns["SetName"].HeaderText = "系列名称";

                this.dgList.Columns["ProductID"].HeaderText = "产品编码";
                this.dgList.Columns["ProductName"].HeaderText = "产品名称";
                this.dgList.Columns["TechnicsName"].HeaderText = "工艺名称";
                this.dgList.Columns["CategoryID"].HeaderText = "类别编码";
                this.dgList.Columns["SetID"].HeaderText = "系列编码";
                this.dgList.Columns["ProductFItemID"].HeaderText = "产品内码"; 

                int intCol = 1;
                strSQL = " Select distinct SemiCode,SemiName from dbo.imSemiProduct Order By SemiCode";
                DataTable dtSemiCol = mdbcon.GetDataTable(strSQL);
                foreach (DataRow drSemiCol in dtSemiCol.Rows)
                {
                    this.dgList.Columns["ColSemiCode" + intCol.ToString()].Visible = false;
                    this.dgList.Columns["ColSemiName" + intCol.ToString()].Visible = false;
                    this.dgList.Columns["ColLaborCost" + intCol.ToString()].Visible = false;

                    this.dgList.Columns["ColQty" + intCol.ToString()].HeaderText = CvtFunc.ToString(drSemiCol["SemiName"]) + " 数量";
                    this.dgList.Columns["ColBOMCost" + intCol.ToString()].HeaderText = CvtFunc.ToString(drSemiCol["SemiName"]) + " 材料成本";
                    intCol++;
                }
                {
                    string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < dgList.Columns.Count; i++)
                    {
                        if (ColumnWidthArray.Length == dgList.Columns.Count) dgList.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
                    }
                }
                #endregion

                #region 人工成本

                this.dgList_Labour.Con = mdbcon.Con;
                this.dgList_Labour.Sql = strLoadSQL;

                this.dgList_Labour.Columns["CategoryName"].HeaderText = "类别名称";
                this.dgList_Labour.Columns["SetName"].HeaderText = "系列名称";

                this.dgList_Labour.Columns["ProductID"].HeaderText = "产品编码";
                this.dgList_Labour.Columns["ProductName"].HeaderText = "产品名称";
                this.dgList_Labour.Columns["TechnicsName"].HeaderText = "工艺名称";
                this.dgList_Labour.Columns["CategoryID"].HeaderText = "类别编码";
                this.dgList_Labour.Columns["SetID"].HeaderText = "系列编码";
                this.dgList_Labour.Columns["ProductFItemID"].HeaderText = "产品内码"; 
                intCol = 1;
                strSQL = " select distinct SemiCode,SemiName from dbo.imSemiProduct Order By SemiCode";
                dtSemiCol = mdbcon.GetDataTable(strSQL);
                foreach (DataRow drSemiCol in dtSemiCol.Rows)
                {
                    this.dgList_Labour.Columns["ColSemiCode" + intCol.ToString()].Visible = false;
                    this.dgList_Labour.Columns["ColSemiName" + intCol.ToString()].Visible = false;
                    this.dgList_Labour.Columns["ColBOMCost" + intCol.ToString()].Visible = false;

                    this.dgList_Labour.Columns["ColQty" + intCol.ToString()].HeaderText = CvtFunc.ToString(drSemiCol["SemiName"]) + " 数量";
                    this.dgList_Labour.Columns["ColLaborCost" + intCol.ToString()].HeaderText = CvtFunc.ToString(drSemiCol["SemiName"]) + " 人工成本";
                    intCol++;
                }
                {
                    string[] ColumnWidthArray = DataFunctions.GetGridColumnWidthString(this.Name, this.CurrentMenuInfo.iParameter, SysVar.UserName, this.Name + "." + this.dgList_Labour.Name).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < dgList_Labour.Columns.Count; i++)
                    {
                        if (ColumnWidthArray.Length == dgList_Labour.Columns.Count) dgList_Labour.Columns[i].Width = CvtFunc.ToInt(ColumnWidthArray[i]);
                    }
                }
                #endregion

            }
        }

        private void frmRMProductBOMQry_Load(object sender, EventArgs e)
        {
            InitControl();
            //InitGrid();
            FillTree();
            FillGrid();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            FillGrid(); 
        }

        private void dgList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                string strRecID = CvtFunc.ToString(this.dgList.CurrentRow.Cells["RecID"].Value);
                ShowBOMMtn(strRecID);
            }
        }

        private void ShowBOMMtn(string strRecID)
        {
            
            string strCategoryName = "";
            string strSetName = "";
            string strProductName = "";
            string strTechnicsName = "";
            string strSQL = "select * from rmProductBOMHdr where RecID='" + strRecID + "'";
            DataRow drHdrInfo = mdbcon.GetDataFirstRow(strSQL);
            if (drHdrInfo == null)
            {
                return;
            }
            else
            {
                strCategoryName = CvtFunc.ToString(drHdrInfo["categoryName"]);
                strSetName = CvtFunc.ToString(drHdrInfo["SetName"]);
                strProductName = CvtFunc.ToString(drHdrInfo["ProductName"]);
                strTechnicsName = CvtFunc.ToString(drHdrInfo["TechnicsName"]);
            }
            //frmRMProductBOMMtn frmBOM = new frmRMProductBOMMtn();
            //frmBOM.MdiParent = SysVar.MDIParentForm;
            strRecID = DataFunctions.GetFieldValue("rmProductBOMHdr", "RecID", "ProductName='" + strProductName + "' and TechnicsName='" + strTechnicsName + "'");
            //frmBOM.ShowFromQry(strRecID);

            MenuInfo menuInfo = DataFunctions.GetMenuInfo(mdbcon, DataFunctions.GetFieldValue(mdbcon, "mMenu", "MenuId", "net_ProgName='frmRMProductBOMMtn' and net_Parameter=0"));
            ReflectMethod.ShowForm(menuInfo, FormStatus.Update, CvtFunc.ToLong(strRecID));
              
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillGrid();
        }

        private void tvTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0) //最后一层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " rmProductBOMHdr.ProductID like '" + strMaterialID + "%'";
                mstrNodeCondition = strCond;
            }
            else  //最上层
            {
                string strMaterialID = "";
                strMaterialID = CvtFunc.ToString(e.Node.Text.ToString()).Split('-')[0];
                //this.dgList.FindRecord(strMaterialID, "MaterialTypeID");
                string strCond = " rmProductBOMHdr.ProductID like '" + strMaterialID + "%'";
                mstrNodeCondition = strCond;
            }
            FillGrid();
        }

        private void btnToExcel_Click(object sender, EventArgs e)
        {
            if (tabMain.SelectedTab == tbpBOM)
            {
                ExportToExcel(this.dgList);
            }
            else
            {
                ExportToExcel(this.dgList_Labour);
            }
        }

        private void dgList_Labour_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                string strRecID = CvtFunc.ToString(this.dgList_Labour.CurrentRow.Cells["RecID"].Value);
                ShowBOMMtn(strRecID);
            }
        }

        private void dgList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

    }
}
